package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dto.*;
import com.cskaoyan.user.service.ILoginService;
import jodd.util.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author Tezel
 * @since 2022/07/29 15:26
 */
@Slf4j
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    MemberMapper memberMapper;


    /**
     * 用户登录
     * @author Tezel
     * @date 2022/07/30
     */

    @Override
    public UserLoginResponse login(UserLoginRequest userLoginRequest, HttpServletResponse httpServletResponse) {

        UserLoginResponse response = new UserLoginResponse();

        try {
            //参数验证
            userLoginRequest.requestCheck();

            //验证数据库中是否存在该用户和密码校验,成功返回Id
            Member user = checkUserInfo(userLoginRequest);
            //信息放入response
            BeanUtils.copyProperties(user, response);

            //验证登录成功,生成JWT Token
            //会在JWT Token字符串，保存用户{"uid":1, "username":"zs"}
            UserInfoToken userInfoToken = new UserInfoToken();
            userInfoToken.setUid(user.getId());
            userInfoToken.setUsername(user.getUsername());
            String msg = JSON.toJSONString(userInfoToken);

            String token = JwtTokenUtils.builder().msg(msg).build().creatJwtToken();

            response.setToken(token);
            response.setCode(UserRetCode.SUCCESS.getCode());
            response.setMsg(UserRetCode.SUCCESS.getMessage());

            //将JWT token放入cookie
            Cookie cookie = CookieUtil.genCookie("access_token", token, "/", 86400);
            httpServletResponse.addCookie(cookie);


        }catch (Exception e){
            log.error("LoginServiceImpl.validateLoginCode occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }


        return response;
    }


    private Member checkUserInfo(UserLoginRequest userLoginRequest) {

        String userPassword = DigestUtils.md5DigestAsHex(userLoginRequest.getPassword().getBytes());

        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", userLoginRequest.getUserName())
                .andEqualTo("password", userPassword);

        List<Member> members = memberMapper.selectByExample(example);

        if(CollectionUtils.isEmpty(members)){
            throw new ValidateException(UserRetCode.USERORPASSWORD_ERRROR.getCode(),UserRetCode.USERORPASSWORD_ERRROR.getMessage());
        }

        //不为空只有一条数据
        Member member = members.get(0);

        //TODO 判断用户是否激活
        if("N".equals(member.getIsVerified())){
            throw new ValidateException(UserRetCode.USER_ISVERFIED_ERROR.getCode(),UserRetCode.USER_ISVERFIED_ERROR.getMessage());
        }


        return member;

    }

    /**
     * 登录验证
     * @author Tezel
     * @date 2022/07/30
     */
    @Override
    public LoginVerifyResponse queryMember(QueryMemberRequest request) {

        LoginVerifyResponse response = new LoginVerifyResponse();

        Member member = memberMapper.selectByPrimaryKey(request.getUserId());

        response.setUid(member.getId());
        response.setUsername(member.getUsername());
        //response.setFile(member.getFile());
        response.setFile("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80");

        return response;
    }


}
